package com.ming.common.liteflow.core.node;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    /**
     * 将新Bean注册到Spring容器
     * @param beanName 要注册的 Bean 的名称。
     * @param bean 要注册的 Bean 实例。
     * @param <T>
     */
    public static <T> void registerBean(String beanName, T bean){
        ((ConfigurableApplicationContext) context).getBeanFactory().registerSingleton(beanName, bean);
    }

    // 从Spring容器中移除Bean
//    public static <T> void destroyBean(String beanName){
//        ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) context;
//        Object bean = getBean(beanName);
//        ctx.getBeanFactory().destroyBean(bean);
//        ctx.getBeanFactory().destroyBean(beanName, bean);
//    }

//    public static <T> void updateBean(String beanName, T bean){
//        // 如果Bean的作用域是prototype，你可能需要手动销毁并重新创建Bean
//        ((ConfigurableApplicationContext) context).getBeanFactory().destroyBean(beanName);
//        registerBean(beanName, bean);
//    }

    public static <T> T getBean(String beanName){
        // 通过Bean的名称获取Bean实例
        try {
            return (T) context.getBean(beanName);
        }catch (Exception e){

        }
        return null;
    }
}
